import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import Qs from 'qs'
import { getAuthentication } from '@/utils/store'

// create an axios instance
const service = axios.create({
  withCredentials: true, // send cookies when cross-domain requests
  timeout: 600000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent
    config.baseURL = store.state.app.server_api

    // 重新组装参数
    if (config.data) {
      let type = config.contentType || 'qs'
      if (!(config.data instanceof FormData) && type === 'qs') {
        config.data = Qs.stringify(config.data, {arrayFormat: 'brackets'})
      } else if (type === 'json') {
        config.headers['Content-Type'] = 'application/json;charset=UTF-8'
        config.data = JSON.stringify(config.data)
      }
    }

    if (!config.headers.TenantHeader) {
      config.headers.TenantHeader = 'Basic cGllY2UtdnVlLXNlcnZpY2U6cGllY2UtdnVl'
    }
    if (!config.headers.Authorization && getAuthentication()) {
      config.headers.Authorization = 'Bearer ' + getAuthentication()
    }

    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
  */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    const res = response.data
    // 非固定格式返回数据，直接返回
    if (res.code === undefined || res.code === null) {
      return res
    }

    // 返回错误信息
    if (res.code !== 200) {
      let message = res.msg || ''
      // 账号登录问题
      if (message.indexOf('登录') !== -1 || message.indexOf('authentication') !== -1) {
        Message({
          message: '信息无效，请重新登录',
          type: 'error',
          duration: 3 * 1000
        })
        store.dispatch('user/resetToken').then(() => {
          location.reload()
        })
      } else {
        // 其它问题
        if (res.param) {
          message += ': ' + res.param
        }
        if (message) {
          Message({
            message: message,
            type: 'error',
            duration: 5 * 1000
          })
        }
      }

      return Promise.reject(new Error(message || '出错了'))
    } else {
      return res
    }
  },
  error => {
    console.log(error) // for debug
    if (error.message.indexOf('429') !== -1) {
      error.message = '接口限流,请稍后进行访问!'
    }
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

service.all = function(promise) {
  return axios.all(promise)
}

service.spread = function(promise) {
  return axios.spread(promise)
}

export default service
